//
//  ALDBManage.m
//  ios-loan-assistant
//
//  Created by hcs on 2018/9/11.
//  Copyright © 2018年 guoqingping. All rights reserved.
//

#import "ALDBManage.h"
#define DefaultDBName @"WTJData.sqlite"
#define CacheDBName @"WTJCacheData.sqlite"

#import "ALDBManage+DBUpdate.h"

static ALDBManage *_dbManage = nil;

@implementation ALDBManage

+ (ALDBManage *) standarDBManage {
    if (!_dbManage) {
        _dbManage = [[ALDBManage alloc] init];
    }
    _dbManage.dbType=Default_DB_type;
    if (!_dbManage.defatulBase) {
        [_dbManage initializeDefaultDBWithName:DefaultDBName];
    }
    [_dbManage connect];
    if (_dbManage.checkTable) {
        [_dbManage createTable];
    }
    return _dbManage;
}

+ (ALDBManage *)standarCacheDBManage{
    if (!_dbManage) {
        _dbManage=[[ALDBManage alloc] init];
    }
    _dbManage.dbType=Cache_DB_type;
    if (!_dbManage.cacheBase) {
        [_dbManage initializeCacheDBWithName:CacheDBName];
    }
    [_dbManage connect];
    [_dbManage checkSqlUpdate];
    
    return _dbManage;
}

- (void) dealloc {
    [self close];
}

- (id) init{
    self = [super init];
    if (self) {
    }
    return self;
}

// 连接数据库
- (void) connect {
    switch (_dbType) {
        case Default_DB_type:
        {
            _dataBase=_defatulBase;
            break;
        }
        case Cache_DB_type:
        {
            _dataBase=_cacheBase;
            break;
        }
        default:
            break;
    }
    if (![_dataBase open]) {
        NSLog(@"不能打开数据库");
    }
}

// 关闭连接
- (void) close {
    [_dataBase close];
    _dbManage = nil;
}
- (BOOL)dropGuideTable{
    if ([_dataBase executeUpdate:@"drop table if exists Guide"]) {
        return YES;
    }else{
        return NO;
    }
}
- (BOOL)dropTable:(NSString *)tableName{
    if ([_dataBase executeUpdate:[NSString stringWithFormat:@"drop table if exists %@",tableName]]) {
        return YES;
    }else{
        return NO;
    }
}
- (void)createTable {
    NSArray *tableNames=nil;
    NSDictionary *sqlCreateTables=nil;
    switch (_dbType) {
        case Default_DB_type:
        {
            
            tableNames = @[kUserTableName];
            sqlCreateTables=@{
                              kUserTableName:UserTableCreate
                              };
            break;
        }
        case Cache_DB_type:
        {
            tableNames = @[kCacheTableName];
            sqlCreateTables=@{kCacheTableName:CacheCreate};
            break;
        }
        default:
            break;
    }
    
    for (NSString *tableName in tableNames) {
        if (![self isTableOK:tableName]) {
            NSString *sql = [sqlCreateTables objectForKey:tableName];
            NSLog(@"创建表%@",tableName);
            if ([_dataBase executeUpdate:sql]) {
                NSLog(@"成功");
            } else {
                NSLog(@"失败");
            }
        }
    }
}

// 检查表是否已经存在
- (BOOL)isTableOK:(NSString *)tableName {
    FMResultSet * set = [_dataBase executeQuery:[NSString stringWithFormat:@"select count(*) from sqlite_master where type ='table' and name = '%@'",tableName]];
    [set next];
    NSInteger count = [set intForColumnIndex:0];
    BOOL existTable = !!count;
    
    if (existTable) {
        NSLog(@"%@表已经存在",tableName);
        return YES;
    } else {
        NSLog(@"%@表不存在",tableName);
        return NO;
    }
}

//查询数据
- (FMResultSet*)selectWithSQLStr:(NSString*)sql {
    FMResultSet *rs = [_dataBase executeQuery:sql];
    return rs;
}

// 插入数据
- (BOOL)insertWithSQLStr:(NSString*)sql {
    return [_dataBase executeUpdate:sql];
}

// 修改数据
- (BOOL)updateWithSQLStr:(NSString*)sql {
    return [_dataBase executeUpdate:sql];
}

// 删除数据
- (BOOL)deleteWithSQLStr:(NSString*)sql {
    return [_dataBase executeUpdate:sql];
}

//删除数据库
- (BOOL)deleteSql{
    NSString * docp = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    _name=[docp stringByAppendingPathComponent:DefaultDBName];
    NSLog(@"path=%@",_name);
    NSFileManager * fileManager = [NSFileManager defaultManager];
    BOOL exist = [fileManager fileExistsAtPath:_name];
    if (exist) { //存在
        return [fileManager isDeletableFileAtPath:_name];
    }else{ //不存在
        return YES;
    }
}

- (NSString *)getSqlNamePath{
    NSString * docp = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    _name=[docp stringByAppendingPathComponent:DefaultDBName];
    return docp;
}

#pragma mark dbManage不同创建
- (int) initializeDefaultDBWithName : (NSString *) name{
    _checkTable=NO; //默认
    NSString * docp = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    _default=[docp stringByAppendingPathComponent:DefaultDBName];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    BOOL exist = [fileManager fileExistsAtPath:_default];
    if (!_defatulBase) {
        _defatulBase = [[FMDatabase alloc] initWithPath:_default];
    }
    [self connect];
    if (!exist) {
        [self createTable];
        return 0;
    } else {
        return 1;          // 返回 数据库已经存在
    }
}
- (int) initializeCacheDBWithName : (NSString *) name{
    NSString * docp = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    docp=[docp stringByAppendingPathComponent:[[NSBundle mainBundle] bundleIdentifier]];
    _cache=[docp stringByAppendingPathComponent:CacheDBName];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    BOOL exist = [fileManager fileExistsAtPath:_cache];
    if (!_cacheBase) {
        _cacheBase = [[FMDatabase alloc] initWithPath:_cache];
    }
    [self connect];
    if (!exist) {
        [self createTable];
        return 0;
    } else {
        return 1;          // 返回 数据库已经存在
    }
}
- (int)reCreateTable:(NSString *)tableName{
    NSString * docp = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    _default=[docp stringByAppendingPathComponent:DefaultDBName];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    BOOL exist = [fileManager fileExistsAtPath:_default];
    if (!_defatulBase) {
        _defatulBase = [[FMDatabase alloc] initWithPath:_default];
    }
    [_defatulBase close];
    [self connect];
    if (exist) {
        if ([fileManager isDeletableFileAtPath:_default]) {
            [self dropTable:tableName];
            [self createTable];
            return 0;
        }else{
            return 1;
        }
    }else{
        [self createTable];
        return 0;
    }
}
@end
